//
//  AppDelegate.m
//  YangWifi
//
//  Created by zuoxueliangduyuanzhuo on 2017/5/31.
//  Copyright © 2017年 zuoxueliangduyuanzhuo. All rights reserved.
//

#import "AppDelegate.h"
#import <AlipaySDK/AlipaySDK.h>
#import "AppDelegate+XLTabBarController.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <UMMobClick/MobClick.h>
#import <UMSocialCore/UMSocialCore.h>
#import <RealReachability/RealReachability.h>
#import <PgySDK/PgyManager.h>
#import <PgyUpdate/PgyUpdateManager.h>
#import "ProductInfoList.h"
@interface AppDelegate ()


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [self buildCocoaLumberjack];
    [self setUpPGYConfig];
    [self setKeyBoardConfig];
    [self setUMengAnalyticsConfig];
    [self setUMengShareConfig];
    [GLobalRealReachability startNotifier];
    [self setRootViewController];
//    [self getAllPackageList];
    return YES;
}

- (void)buildCocoaLumberjack
{
    // 添加DDASLLogger，你的日志语句将被发送到Xcode控制台
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
    
    // 添加DDTTYLogger，你的日志语句将被发送到Console.app
    [DDLog addLogger:[DDASLLogger sharedInstance]];
    
    // 添加DDFileLogger，你的日志语句将写入到一个文件中，默认路径在沙盒的Library/Caches/Logs/目录下，文件名为bundleid+空格+日期.log。
    DDFileLogger *fileLogger = [[DDFileLogger alloc] init];
    fileLogger.rollingFrequency = 60 * 60 * 24;
    fileLogger.logFileManager.maximumNumberOfLogFiles = 7;
    [DDLog addLogger:fileLogger];
    
    //产生Log
    DDLogVerbose(@"Verbose");
    DDLogDebug(@"Debug");
    DDLogInfo(@"Info");
    DDLogWarn(@"Warn");
    DDLogError(@"Error");
}


- (void)setRootViewController
{
    self.window.rootViewController = [self xlTabBarController];

}

- (void)setUpPGYConfig
{
    [[PgyUpdateManager sharedPgyManager] startManagerWithAppId:PGY_APPKEY];
    [[PgyUpdateManager sharedPgyManager] checkUpdate];
}

- (void)networkChanged:(NSNotification *)notification
{
    RealReachability *reachability = (RealReachability *)notification.object;
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    DLog(@"currentStatus:%@",@(status));
    
    switch (status)
    {
        case RealStatusNotReachable:
        {
            //  case NotReachable handler
            break;
        }
            
        case RealStatusViaWiFi:
        {
            //  case ReachableViaWiFi handler
            break;
        }
            
        case RealStatusViaWWAN:
        {
            //  case ReachableViaWWAN handler
            break;
        }
            
        default:
            break;
    }
    
}


- (void)setKeyBoardConfig
{
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = NO;
}

- (void)setUMengShareConfig
{
    //打开调试日志
    [[UMSocialManager defaultManager] openLog:YES];
    
    //设置友盟appkey
    [[UMSocialManager defaultManager] setUmSocialAppkey:@"5966f5538f4a9d0a89000f8d"];
    
    // 获取友盟social版本号
    DLog(@"UMeng social version: %@", [UMSocialGlobal umSocialSDKVersion]);
    
    //设置微信的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxfa30df5da8c46ea0" appSecret:@"4f86f354ff4b2ea9e0c6983a368eefae" redirectURL:@"http://www.yaoxz.cn/"];
    
    //设置分享到QQ互联的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1106157073"  appSecret:nil redirectURL:@"http://www.yaoxz.cn/"];
}


- (void)setUMengAnalyticsConfig
{
    UMConfigInstance.appKey = @"5966f5538f4a9d0a89000f8d";
    UMConfigInstance.channelId =@"AppStore";
    UMConfigInstance.ePolicy = BATCH;
    [MobClick startWithConfigure:UMConfigInstance];
    [MobClick setAppVersion:[AccountHanler appLocalVersion]];
    [MobClick setEncryptEnabled:YES];
    [MobClick setLogSendInterval:10000];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)getAllPackageList
{
    NSDictionary *params = @{
                             @"type": @"OSWIFI_PACKAGELIST_MOBILE",
                             @"token":IsNull([AccountHanler token], @""),
                             @"requestEntity":@{
                                     @"telephone":IsNull([AccountHanler telPhone], @"")                                     }
                             };
    [MHNetworkManager postReqeustWithURL:nil params:params successBlock:^(NSDictionary *returnData) {
        DLog(@"returnData---->%@",[returnData mj_JSONString]);
        
        XLBaseModel *result = [XLBaseModel mj_objectWithKeyValues:returnData];
        if (result.resultFlag) {
            
            
            ProductInfoList *list =[ProductInfoList mj_objectWithKeyValues:returnData];
            [AccountHanler savePackageList:[list mj_JSONString]];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"packageList" object:nil];

        }else{
            DLog(@"套餐获取失败");
        }
        
    } failureBlock:^(NSError *error) {
        DLog(@"error---->%@",error.localizedDescription);
    } showHUD:NO];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    return YES;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    return YES;
}


@end
